<?php
class UploadfilesController extends AppController {

	var $name = 'Uploadfiles';
	var $uses = array ('Uploadfile');	
	var $helpers = array('Html', 'Form', 'Javascript', 'Tinymce');
	var $components = array ('Upload');	
	var $layout = 'admin';
		
	function index() {
		$this->set('uploadfiles', $this->paginate('Uploadfile'));
	}

	function add()
	{
		if(! empty ($this->data))
		{
			$this->Uploadfile->create ();
			if($this->Upload->upload ($this->data['Uploadfile']['file'], WWW_ROOT . 'files' . DS , false))
			{
				$this->data['Uploadfile']['name'] = $this->data['Uploadfile']['file']['name'];
			}
			if($this->Uploadfile->save ($this->data))
			{
				$this->Session->setFlash (__ ('đã được thêm', true));
				$this->redirect (array('action' => 'index'));
			}else
			{
				$this->Session->setFlash (__ ('Không thêm được', true));
			}
		}
	}
	
	function edit($id = null)
	{
		$uploadfiles = $this->Uploadfile->read (null, $id);
		if(! $id && empty ($this->data))
		{
			$this->Session->setFlash (__ ('Invalid id', true));
			$this->redirect (array('action' => 'index'));
		}
		if(! empty ($this->data))
		{
			if($this->data['Uploadfile']['file']['name'])
			{
				if(! $this->Upload->upload ($this->data['Uploadfile']['file'], WWW_ROOT . 'files' . DS , false))
				{
					$this->Session->setFlash (__ ('Upload File Fail', true));
					$this->redirect (array('action' => 'edit/' . $id));
				}
				@unlink (WWW_ROOT . 'files' . DS . $uploadfiles['Uploadfile']['name']);
				$this->data['Uploadfile']['name'] = $this->data['Uploadfile']['file']['name'];
			}
			if($this->Uploadfile->save ($this->data))
			{
				$this->Session->setFlash (__ ('The File has been saved', true));
				$this->redirect (array('action' => 'index'));
			}else
			{
				$this->Session->setFlash (__ ('The File could not be saved. Please, try again.', true));
			}
		}
		
		if(empty ($this->data))
		{
			$this->data = $uploadfiles;
		}
	}
	
	function delete($id = null)
	{
		if(! $id)
		{
			$this->Session->setFlash (__ ('Invalid id for File', true));
			$this->redirect (array('action' => 'index'));
		}
		$del_file = $this->Uploadfile->findById ($id);
		if($this->Uploadfile->del ($id))
		{
			@unlink (WWW_ROOT . 'files' . DS . $del_file['Uploadfile']['name']);
			$this->Session->setFlash (__ ('File deleted', true));
			$this->redirect (array('action' => 'index'));
		}
	}
}
?>